﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Fuse8.ContentManagementFramework.BizFacade.Services.Contents.Queryable
{
    public class ContentQueryExpressionValidator: ExpressionVisitor
    {
        public IList<KeyValuePair<string, Expression>> Expressions { get; private set; }

        public ContentQueryExpressionValidator()
        {
            Expressions = new List<KeyValuePair<string, Expression>>();
        }

        public void Parse(Expression expression)
        {
            Visit(expression);            
        }

        protected override Expression VisitMethodCall(MethodCallExpression expression)
        {
            if (SupportedQueryableOperationsFacade.Operations.ContainsKey(expression.Method.Name))
            {
                Expressions.Add(new KeyValuePair<string, Expression>(expression.Method.Name,
                                                                     SupportedQueryableOperationsFacade.Operations[
                                                                         expression.Method.Name].Converter(expression)));
            }
            else
            {
                throw new NotSupportedException(string.Format("Operation {0} is not supported", expression.Method.Name));
            }

            Visit(expression.Arguments[0]);

            return expression;
        }
    }             
}